package com.sz.mes.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.vo.JsonResult;
import com.sz.mes.entity.Warehouse;
import com.sz.mes.entity.warehouse.Area;
import com.sz.mes.entity.warehouse.Shelves;
import com.sz.mes.mapper.WarehouseMapper;
import com.sz.mes.mapper.warehouse.AreaMapper;
import com.sz.mes.mapper.warehouse.ShelvesMapper;
import com.sz.mes.service.WarehouseService;
import com.sz.mes.service.impl.BaseCustomServiceImpl;
import com.sz.mes.vo.WarehouseListVO;
import com.sz.mes.vo.warehouse.AreaListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 仓库相关Service实现
 *
 * @author hem
 * @version 1.0
 * @date 2023-05-25
 * Copyright © szhs
 */
@Service
@Slf4j
public class WarehouseServiceImpl extends BaseCustomServiceImpl<WarehouseMapper, Warehouse> implements WarehouseService {

    private final WarehouseMapper warehouseMapper;
    private final AreaMapper areaMapper;
    private final ShelvesMapper shelvesMapper;

    public WarehouseServiceImpl(WarehouseMapper warehouseMapper, AreaMapper areaMapper, ShelvesMapper shelvesMapper) {
        this.warehouseMapper = warehouseMapper;
        this.areaMapper = areaMapper;
        this.shelvesMapper = shelvesMapper;
    }

    @Override
    public JsonResult getTreeWarehouse() {
        QueryWrapper<Warehouse> wrapper = new QueryWrapper<>();
        wrapper.eq("is_deleted", 0);
        List<Warehouse> warehouses = warehouseMapper.selectList(wrapper);

        List<WarehouseListVO> warehouseListVOS = BeanUtils.convertList(warehouses, WarehouseListVO.class);

        for (WarehouseListVO warehouseListVO : warehouseListVOS) {
            QueryWrapper<Area> areaQueryWrapper = new QueryWrapper<>();
            areaQueryWrapper.eq("is_deleted", 0);
            areaQueryWrapper.eq("warehouse_id", warehouseListVO.getId());
            List<Area> areas = areaMapper.selectList(areaQueryWrapper);

            List<AreaListVO> areaListVOS = BeanUtils.convertList(areas, AreaListVO.class);

            for (AreaListVO areaListVO : areaListVOS) {
                QueryWrapper<Shelves> shelvesQueryWrapper = new QueryWrapper<>();
                shelvesQueryWrapper.eq("is_deleted", 0);
                shelvesQueryWrapper.eq("warehouse_area_id", areaListVO.getId());
                List<Shelves> shelves = shelvesMapper.selectList(shelvesQueryWrapper);
                areaListVO.setShelves(shelves);
            }
            warehouseListVO.setAreaListVOS(areaListVOS);
        }
        return JsonResult.OK(warehouseListVOS);
    }
}
